var net = require('net');
var util = require('util');
var uuid = require('node-uuid');
var xml2js = require('xml2js');
require('./js2xml');

var server = net.createServer();
var parser = new xml2js.Parser({
	explicitArray : true,
	explicitRoot : true,
	mergeAttrs : true
});

server.on('connection', function(socket) {
	socket.on('data', function(data) {
		parser.parseString(data, function(err, req) {
			console.log(JSON.stringify(req));
			var request = req.request;
			var response = "";
			
			if (typeof(request.addChoiceRequest) != "undefined") {
				response = '<response version="1.0" id="589a39591271844e3fbe32bbb9281ad9" success="true">' + 
							'<addChoiceResponse id="sdjklakj3s" number="3" choice="TGIF\'s"/></response>';
			}
			else if (typeof(request.addEdgeRequest[0]) != "undefined") {
				var command = request.addEdgeRequest[0] || {};
				
				var responseO = {};
				responseO.setXMLClass("response");
				responseO.id = request.id || uuid.v4();
				responseO.version = "1.0";
				
				
				console.log(util.inspect(request));
				
				var addEdge = {};
				addEdge.setXMLClass("addEdgeResponse");
				addEdge.id = command.id || "0";
				addEdge.height = command.height || 0;
				addEdge.left = command.left || 0;
				addEdge.right = command.right || 1;
				
				responseO.__XMLchildren = addEdge;
				
				response = responseO.toXML();
					
//					'<response version="1.0" id="589a39591271844e3fbe32bbb9281ad9" success="true">' +
//							'<addEdgeResponse id="alkj3ksjd" left="3" right="4" height="137"/></response>';
			}
			else if (typeof(request.createRequest) != "undefined") {
				response = '<response version="1.0" id="589a39591271844e3fbe32bbb9281ad9" success="true">' +
							'<createResponse id="sjlk2sjkl"/></response>';
			}
			else if (typeof(request.signInRequest) != "undefined") {
				response = '<response version="1.0" id="589a39591271844e3fbe32bbb9281ad9" success="true">' +
							'<signInResponse id="asdklj23" type="open" question="where to eat?" numChoices="4"' +
							'numRounds="3" position="4"><choice value="McDonald\'s" index="1"/><choice value="Wendy\'s" index="2"/>' +
							'<choice value="Burger King" index="3"/></signInResponse></response>';
			}

			console.log("Sending " + response);
			socket.write(response);
		});
	});
});

server.listen(9371, "127.0.0.1", function() {
	console.log("Listening on 127.0.0.1:9371");
});